<template>
  <div class="content">
    <div class="head-top">
      <dc-header :icon="'icon-header-back'" :title="'记一笔'"></dc-header>
      <mt-navbar v-model="selected">
        <mt-tab-item id="2">支出</mt-tab-item>
        <mt-tab-item id="1">收入</mt-tab-item>
      </mt-navbar>
      <mt-tab-container v-model="selected" class="mt30">
        <mt-tab-container-item id="2">
          <dc-row type="flex" justify="end" class="bg-white">
            <dc-col span="5">
              <span class="money">金额</span>
            </dc-col>
            <dc-col span="19">
              <input class="moneynum" type="tel" maxlength="13" placeholder="0" v-model="expenditure.accountNum"/>
            </dc-col>
          </dc-row>
          <div class="mt30">
            <pickerBox v-if="selected === '2'" :slots="slots" :valuekeys="'accountName'"
                       @getValue="getExpenditureCategoryValue" :change="changeValue">
              <mt-cell title="类别" :value="expenditureValue" is-link></mt-cell>
            </pickerBox>
            <inputSelect placeholder="请选择" type="text" showtype="noicon"
                         v-validate="{ rules: { required: true } }"
                         name="记账类型"
                         label="记账类型"
                         :upscrolldata="accountTypelist"
                         v-model="expenditure.accountType"
            ></inputSelect>
            <inputDateselect label="日期" v-if="expenditure.accountType==='1'" datepickerType="nyr"
                             v-model="expenditure.startnyr"></inputDateselect>
            <inputDateselect name="起始时间" label="起始时间"
                             datepickerType="ny"
                             v-if="expenditure.accountType==='2' || expenditure.accountType==='3'"
                             v-model="expenditure.startny"
            ></inputDateselect>
            <inputSelectCustom placeholder="请选择" type="text" showtype="noicon"
                               v-validate="{ rules: { required: true } }"
                               name="持续周期"
                               label="持续周期"
                               :upscrolldata="timeSlot"
                               v-model="expenditure.duration"
                               v-if="expenditure.accountType==='3'"
            >
              <mt-cell :title="'持续周期'" v-model="expenditureDurationLaber" is-link></mt-cell>
            </inputSelectCustom>
            <inputSelectCustom placeholder="请选择" type="text" showtype="noicon"
                               v-validate="{ rules: { required: true } }"
                               name="摊销周期"
                               label="摊销周期"
                               :upscrolldata="timeSlot"
                               v-model="expenditure.duration"
                               v-if="expenditure.accountType==='2'"
            >
              <mt-cell :title="'摊销周期'" v-model="expenditureDurationLaber" is-link></mt-cell>
            </inputSelectCustom>
            <!--<mt-cell title="摊销周期" v-if="expenditure.accounttype==='3'" value="三个月" is-link></mt-cell>-->
          </div>
          <div class="mt30">
            <mt-field class="kctextleft" :attr="{maxlength:200}" label="备注" placeholder="请输入" v-model="expenditure.remark"></mt-field>
          </div>
          <div class="buttonBox">
            <dc-row type="flex" justify="start">
              <dc-col span="12" type="default" class="leftbuttonBox">
                <mt-button @click="pushExpenditure(true)">保存</mt-button>
              </dc-col>
              <dc-col type="primary" span="12" class="rightbuttonBox">
                <mt-button @click="pushExpenditure(false)">保存并记录下一条</mt-button>
              </dc-col>
            </dc-row>
          </div>
        </mt-tab-container-item>
        <mt-tab-container-item id="1">
          <dc-row type="flex" justify="end" class="bg-white">
            <dc-col span="5">
              <span class="money">金额</span>
            </dc-col>
            <dc-col span="19">
              <input class="moneynum green" type="tel" maxlength="13" placeholder="0" v-model="income.accountNum"/>
            </dc-col>
          </dc-row>
          <div class="mt30">
            <pickerBox v-if="selected === '1'" :slots="slots" :valuekeys="'accountName'"
                       @getValue="getIncomeCategoryValue" :change="changeValue">
              <mt-cell title="类别" :value="incomeValue" is-link></mt-cell>
            </pickerBox>
            <inputSelect placeholder="请选择" type="text" showtype="noicon"
                         v-validate="{ rules: { required: true } }"
                         name="记账类型"
                         label="记账类型"
                         :upscrolldata="accountTypelist2"
                         v-model="income.accountType"
            ></inputSelect>
            <inputDateselect label="日期" v-if="income.accountType==='1'" datepickerType="nyr"
                             v-model="income.startnyr"></inputDateselect>
            <inputDateselect name="起始日期" label="起始日期"
                             datepickerType="ny"
                             v-if="income.accountType==='2' || income.accountType==='3'"
                             v-model="income.startny"
            ></inputDateselect>
            <inputSelectCustom placeholder="请选择" type="text" showtype="noicon"
                               v-validate="{ rules: { required: true } }"
                               name="持续周期"
                               label="持续周期"
                               :upscrolldata="timeSlot"
                               v-model="income.duration"
                               v-if="income.accountType==='2'"
            >
              <mt-cell :title="'持续周期'" v-model="incomeDurationLaber" is-link></mt-cell>
            </inputSelectCustom>
            <inputSelectCustom placeholder="请选择" type="text" showtype="noicon"
                               v-validate="{ rules: { required: true } }"
                               name="摊销周期"
                               label="摊销周期"
                               :upscrolldata="timeSlot"
                               v-model="income.duration"
                               v-if="income.accountType==='3'"
            >
              <mt-cell :title="'摊销周期'" v-model="incomeDurationLaber" is-link></mt-cell>
            </inputSelectCustom>
            <!--<mt-cell title="摊销周期" v-if="expenditure.accounttype==='3'" value="三个月" is-link></mt-cell>-->
          </div>
          <div class="mt30">
            <mt-field class="kctextleft" :attr="{maxlength:200}" label="备注" placeholder="请输入" v-model="income.remark"></mt-field>
          </div>
          <div class="buttonBox">
            <dc-row type="flex" justify="start">
              <dc-col span="12" type="default" class="leftbuttonBox">
                <mt-button @click="pushExpenditure(true)">保存</mt-button>
              </dc-col>
              <dc-col type="primary" span="12" class="rightbuttonBox">
                <mt-button @click="pushExpenditure(false)">保存并记录下一条</mt-button>
              </dc-col>
            </dc-row>
          </div>
        </mt-tab-container-item>
      </mt-tab-container>
    </div>
  </div>
</template>
<script>
  import header from '@/common/plugins/header';
  import {col, row} from '@/common/Flex';
  import inputSelectCustom from '@/common/plugins/input/inputSelectCustom.vue';
  import inputDateselect from '@/common/plugins/input/inputDateselect.vue';
  import inputSelect from '@/common/plugins/input/inputSelect.vue';
  import pickerBox from '@/common/plugins/pickerBox.vue';
  import api from '../../../common/api/account';
  import mintUi from '@/common/mintUi';
  let timeSlot = [{
    label: '3个月',
    value: '1'
  }, {
    label: '6个月',
    value: '2'
  }, {
    label: '9个月',
    value: '3'
  }, {
    label: '12个月',
    value: '4'
  }, {
    label: '24个月',
    value: '5'
  }, {
    label: '自定义',
    value: '6'
  }];

  export default {
    data () {
      return {
        selected: '2',
        accountTypelist: [{
          label: '单次支出',
          value: '1'
        }, {
          label: '固定支出',
          value: '3'
        }, {
          label: '摊销费用',
          value: '2'
        }],
        accountTypelist2: [{
          label: '单次收入',
          value: '1'
        }],
        timeSlot: timeSlot,
        slots: [
          {
            flex: 1,
            defaultIndex: 0,
            values: [],
            className: 'slot1',
            textAlign: 'center'
          }, {
            flex: 1,
            defaultIndex: 0,
            values: [],
            className: 'slot3',
            textAlign: 'center'
          }
        ],
        expenditure: {
          accountCode: '',
          accountSubCode: '',
          accountType: '1',
          duration: '',
          durationLaber: '',
          startnyr: this.getYMD('nyr'),
          startny: this.getYMD('ny'),
          accountNum: '',
          remark: ''
        },
        expenditureDurationLaber: '请选择',
        income: {
          accountCode: '',
          accountSubCode: '',
          accountType: '1',
          duration: '',
          durationLaber: '',
          startnyr: this.getYMD('nyr'),
          startny: '请选择',
          accountNum: '',
          remark: ''
        },
        incomeDurationLaber: '请选择',
        expenditureValue: '请选择',
        incomeValue: '请选择'
      };
    },
    methods: {
      getExpenditureCategoryValue: function (e) {
        this.expenditureValue = e[0].accountName + (e[1] ? '>' + e[1].accountName : '');
        this.expenditure.accountCode = e[0].accountCode;
        this.expenditure.accountSubCode = e[1] ? e[1].accountCode : '';
      },
      getIncomeCategoryValue: function (e) {
        this.incomeValue = e[0].accountName + (e[1] ? '>' + e[1].accountName : '');
        this.income.accountCode = e[0].accountCode;
        this.income.accountSubCode = e[1] ? e[1].accountCode : '';
      },
      changeValue: function (picker, values) {
        if (values[0]) {
          let arr = this.slots[0].values.filter(function (val) {
            if (val.accountCode === values[0].accountCode) {
              return val;
            }
          });
          // this.slots[1].values = arr[0].subCategory;
          picker.setSlotValues(1, arr[0].subCategory || []);
        }
      },
      openPrompt: function (mes, obj) {
        let that = this;
        mintUi.openPrompt(mes, {inputType: 'number'}).then(function (e) {
          if (parseInt(e) && parseInt(e) < 120) {
            that[obj] = parseInt(e) + '个月';
            that.income.duration = '';
            that.expenditure.duration = '';
          } else {
            that.openPrompt('您输入的月份无效', obj);
          }
        }, function () {
          that.income.duration = '';
          that.expenditure.duration = '';
        }).catch(function () {
          that.income.duration = '';
          that.expenditure.duration = '';
        });
      },
      pushExpendi (e) {
        let that = this;
        let data = JSON.parse(JSON.stringify(this.expenditure));
        data.duration = parseInt(this.expenditureDurationLaber);
        data.accountFlag = this.selected;
        let beginTime = this.expenditure.accountType === '1' ? this.expenditure.startnyr : this.expenditure.startny;
        let beginTimeArr = beginTime.split('-');
        data.beginTime = Date.parse(new Date(beginTimeArr[0], beginTimeArr[1] - 1, beginTimeArr[2] || 1));
        if (!data.beginTime || (data.accountCode !== 1 ? false : (!data.duration)) || !data.accountCode || !data.accountNum) {
          mintUi.openToast('请填写完整信息');
          return;
        }
        if ((+new Date()) - data.beginTime > 365 * 24 * 60 * 60 * 1000) {
          mintUi.openToast('请选择一年以内的数据');
          return;
        }
        var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
        if (!reg.test(data.accountNum)) {
          mintUi.openToast('请填写数字金额');
          return;
        }

        api.pushcategoryitem(data).then(function (res) {
          if (e) {
            that.$router.go(-1);
          } else {
            mintUi.openToast('成功');
            that.expenditure.accountNum = '';
            that.income.accountNum = '';
            that.expenditure.remark = '';
            that.income.remark = '';
          }
        });
      },
      pushIncomei (e) {
        let that = this;
        let data = JSON.parse(JSON.stringify(this.income));
        data.duration = parseInt(this.incomeDurationLaber);
        data.accountFlag = this.selected;
        let beginTime = this.income.accountType === '1' ? this.income.startnyr : this.income.startny;
        let beginTimeArr = beginTime.split('-');
        data.beginTime = Date.parse(new Date(beginTimeArr[0], beginTimeArr[1] - 1, beginTimeArr[2] || 1));
        if (!data.beginTime || (data.accountCode !== 1 ? false : (!data.duration)) || !data.accountCode || !data.accountNum) {
          mintUi.openToast('请填写完整信息');
          return;
        }
        if ((+new Date()) - data.beginTime > 365 * 24 * 60 * 60 * 1000) {
          mintUi.openToast('请选择一年以内的数据');
          return;
        }
        var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
        if (!reg.test(data.accountNum)) {
          mintUi.openToast('请填写数字金额');
          return;
        }
        api.pushcategoryitem(data).then(function (res) {
          if (e) {
            that.$router.go(-1);
          } else {
            mintUi.openToast('成功');
            that.expenditure.accountNum = '';
            that.income.accountNum = '';
            that.expenditure.remark = '';
            that.income.remark = '';
          }
        });
      },
      pushExpenditure (e) {
        if (this.selected === '2') {
          this.pushExpendi(e);
        } else {
          this.pushIncomei(e);
        }
      },
      getYMD (type) {
        let newDate = new Date();
        if (type === 'nyr') {
          return newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate();
        } else {
          return newDate.getFullYear() + '-' + (newDate.getMonth() + 1);
        }
      }
    },
    watch: {
      selected: function () {
        api.getcategoryList({'accountFlag': this.selected}).then(res => { //点击单个选项获取店铺列表api
          this.slots[0].values = res || [];
          this.slots[1].values = res && (res[0].subCategory || []);
        });
      },
      income: {
        handler (newValue, oldValue) {
          if (newValue.duration === '6') {
            this.openPrompt('请输入具体月份', 'incomeDurationLaber');
          } else {
            this.incomeDurationLaber = timeSlot[newValue.duration - 1] ? timeSlot[newValue.duration - 1].label : '';
          }
        },
        deep: true
      },
      'expenditure.duration': {
        handler (newValue, oldValue) {
          if (newValue === '6') {
            this.openPrompt('请输入具体月份', 'expenditureDurationLaber');
          } else {
            this.expenditureDurationLaber = timeSlot[newValue - 1] ? timeSlot[newValue - 1].label : this.expenditureDurationLaber;
          }
        },
        deep: true
      }
    },
    created () {
      if (this.$route.query.accountType) {
        this.selected = this.$route.query.accountType + '';
        // this.income.accountType = this.$route.query.accountType + '';
      };
      api.getcategoryList({'accountFlag': this.selected}).then(res => { //点击单个选项获取店铺列表api
        this.slots[0].values = res || [];
        this.slots[1].values = res && (res[0].subCategory || []);
      });
    },
    components: {
      'dc-header': header,
      'dc-col': col,
      'dc-row': row,
      inputSelect,
      inputDateselect,
      inputSelectCustom,
      pickerBox
    }
  };
</script>
<style lang="scss" scoped>
  @import "../../../assets/css/variable";

  .money {
    line-height: px2rem(140px);
    font-size: px2rem(35px);
    font-weight: bold;
  }

  .moneynum {
    height: px2rem(140px);
    border: none;
    outline: none;
    text-align: right;
    color: #f8c840;
    font-size: px2rem(50px);
    padding: 0;
    margin: 0;
    width: 90%;
  }

  .green {
    color: #59cd9c;
  }

  .buttonBox {
    position: fixed;
    bottom: 0;
    width: 100%;
  }

  .leftbuttonBox {
    height: px2rem(100px);
    background: #456878;
    button {
      color: $theme-color;
      background: #fdfdfd;
    }
  }

  .rightbuttonBox {
    height: px2rem(100px);
    background: #456878;
    button {
      color: #fff;
      background: $theme-color;
    }
  }

  .rightbuttonBox, .leftbuttonBox {
    button {
      width: 100%;
      border-radius: 0;
      box-shadow: none;
      height: px2rem(100px);
      font-size: px2rem(30px);
    }
  }
</style>
<style lang="scss">
  .kctextleft .mint-field-core {
    text-align: right;
  }
</style>
